#include "TriangleParser.h"


TriangleParser::TriangleParser(void)
{
}


TriangleParser::~TriangleParser(void)
{
}

TriangleParser::TriangleParser(float x1, float y1, float z1, float x2, float y2, float z2, float x3 , float y3, float z3, string tx_id, string mat_id):
PrimitiveParser(tx_id, mat_id)
{
	this->x1 = x1;
	this->y1 = y1;
	this->z1 = z1;
	this->x2 = x2;
	this->y2 = y2;
	this->z2 = z2;
	this->x3 = x3;
	this->y3 = y3;
	this->z3 = z3;

	float ux = x2 - x1;
	float uy = y2 - y1;
	float uz = z2 - z1;

	float vx = x3 - x1;
	float vy = y3 - y1;
	float vz = z3 - z1;

	nx = uy*vz - uz*vy;
	ny = uz*vx - ux*vz;
	nz = ux*vy - uy*vx;

	/*float n_length = sqrt(nx*nx + ny*ny + nz*nz);

	nx /= n_length;
	ny /= n_length;
	nz /= n_length;*/

	//paulbourke.net/geometry/pointline
	float u = (vx*ux + vy*uy + vz*uz) / (ux*ux + uy*uy + uz*uz);
	float x1_2 = x1 + u*ux;
	float y1_2 = y1 + u*uy;
	float z1_2 = z1 + u*uz;

	p3_length = sqrt( (x1_2 - x1)*(x1_2 - x1)  + (y1_2 - y1)*(y1_2 - y1) + (z1_2 - z1)*(z1_2 - z1));
	length = sqrt( (x2 - x1)*(x2 - x1)  + (y2 - y1)*(y2 - y1) + (z2 - z1)*(z2 - z1));
	height = sqrt( (x1_2 - x3)*(x1_2 - x3)  + (y1_2 - y3)*(y1_2 - y3) + (z1_2 - z3)*(z1_2 - z3));
}

void TriangleParser::render(){
	if(texture_id != "none" && texture_id != "inherit")
		render(texture);
	else{
		glBegin(GL_POLYGON);
			glNormal3d(nx,ny,nz);
			glVertex3f(x1,y1,z1);
			glVertex3f(x2,y2,z2);
			glVertex3f(x3,y3,z3);
		glEnd();
	}
}

void TriangleParser::render(TextureParser* tx){
	float txX = length/ tx->length_s;
	float txY = height/ tx->length_t;
	float txX_p3 = p3_length/ tx->length_s;

	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D, tx->tx_id);
	glBegin(GL_POLYGON);
		glNormal3d(nx,ny,nz);
		glTexCoord2f(0.0,0.0); glVertex3f(x1,y1,z1);
		glTexCoord2f(txX,0.0); glVertex3f(x2,y2,z2);
		glTexCoord2f(txX_p3,txY); glVertex3f(x3,y3,z3);
	glEnd();
	glDisable(GL_TEXTURE_2D);
}